# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 单一聚合last操作.py
# @Author: dongguangwen
# @Date  : 2025-06-14 20:28
from pymongo import MongoClient

# 连接到MongoDB（默认端口27017）
client = MongoClient('mongodb://root:root123@192.168.1.119:27017/')

# 创建数据库和集合
db = client['learning_mongodb']
collection = db['users']


pipeline = [
    {"$sort": {"age": 1}},
    {
        "$group": {
            "_id": None,
            "oldest_user": {"$last": "$name"}
        }
    }
]
result = list(db.users.aggregate(pipeline))
print(result)
print("最年长的用户:", result[0]["oldest_user"])

"""
[{'_id': None, 'oldest_user': 'User_4'}]
最年长的用户: User_4
"""
